<template>
  <div class="user-home">
    <h2>欢迎回来，{{ username }}！</h2>
    <p class="welcome-text">这里是图书查询系统，您可以浏览所有图书信息</p>
    <el-card>
      <div slot="header" class="clearfix">
        <span>图书信息</span>
      </div>
      <el-table
        v-loading="loading"
        :data="bookList"
        border
        style="width: 100%"
        empty-text="暂无图书数据">
        <el-table-column prop="id" label="编号" width="80" align="center"></el-table-column>
        <el-table-column prop="name" label="图书名" width="150"></el-table-column>
        <el-table-column prop="author" label="作者" width="120"></el-table-column>
        <el-table-column prop="publish" label="出版社" width="180"></el-table-column>
        <el-table-column prop="pages" label="页数" width="80" align="center"></el-table-column>
        <el-table-column prop="price" label="价格" width="100" align="center">
          <template slot-scope="scope">
            {{ scope.row.price ? scope.row.price.toFixed(2) : 'N/A' }}
          </template>
        </el-table-column>
        <el-table-column prop="bookcaseid" label="书架ID" width="80" align="center"></el-table-column>
      <el-table-column prop="abled" label="状态" width="80" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.abled === 1 ? 'success' : 'danger'">
            {{ scope.row.abled === 1 ? '可用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" align="center">
        <template slot-scope="scope">
          <el-button 
            v-if="scope.row.abled === 1"
            type="primary" 
            size="mini"
            @click="handleBorrow(scope.row)">
            借阅
          </el-button>
        </template>
      </el-table-column>
      </el-table>
      <el-pagination
        background
        layout="prev, pager, next"
        :page-size="pageSize"
        :total="total"
        @current-change="page"
        style="margin-top: 20px">
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'UserHome',
  data() {
    return {
      username: localStorage.getItem('username') || '用户',
      bookList: [],
      pageSize: 6,
      total: 0,
      loading: false
    }
  },
  methods: {
    handleBorrow(book) {
      if (!localStorage.getItem('username')) {
        this.$message.warning('请先登录');
        this.$router.push('/login');
        return;
      }
      // 获取图书完整信息验证状态
      axios.get(`http://localhost:8181/book/findById/${book.id}`)
        .then(resp => {
          if (!resp.data || resp.data.abled !== 1) {
            this.$message.warning('该图书已被借阅');
            return;
          }
          this.$confirm(`确认借阅《${book.name}》吗?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
      const userIdStr = localStorage.getItem('userId');
      if (!userIdStr || isNaN(userIdStr)) {
        this.$message.error('用户ID无效，请重新登录');
        this.$router.push('/login');
        return;
      }
      const userId = parseInt(userIdStr);
            axios.post('http://localhost:8181/borrow', {
              book: { id: book.id },
              user: { id: userId }
            }).then(resp => {
              if (resp.data === 'success') {
                this.$message.success('借阅请求已提交，等待管理员批准');
                this.page(this.currentPage); // 刷新数据
              }
            }).catch(error => {
              const errorMsg = error.response?.data?.message || error.message;
              this.$message.error('借阅失败: ' + errorMsg);
            });
          }).catch(() => {
            this.$message.info('已取消借阅');
          });
        })
        .catch(error => {
          this.$message.error('检查图书状态失败: ' + error.message);
      }).catch(() => {
        this.$message.info('已取消借阅');
      });
    },
    page(currentPage) {
      this.loading = true
      const _this = this
      axios.get('http://localhost:8181/book/findAll/' + (currentPage - 1) + '/' + this.pageSize)
        .then(function(resp) {
          if (resp.data && resp.data.data) {
            _this.bookList = resp.data.data
            _this.total = resp.data.total
          } else {
            throw new Error('Invalid response format')
          }
        })
        .catch(error => {
          console.error('获取图书数据失败:', error)
        })
        .finally(() => {
          this.loading = false
        })
    }
  },
      created() {
      // 直接从localStorage获取用户ID
      const userId = localStorage.getItem('userId');
      if (!userId) {
        this.$message.error('用户未登录');
        this.$router.push('/login');
        return;
      }

      // 加载图书数据
      this.loading = true
      const _this = this
      axios.get('http://localhost:8181/book/findAll/0/' + this.pageSize)
        .then(function(resp) {
          if (resp.data && resp.data.data) {
            _this.bookList = resp.data.data
            _this.total = resp.data.total
          } else {
            throw new Error('Invalid response format')
          }
        })
        .catch(error => {
          this.$message.error('初始化图书数据失败: ' + error.message)
        })
        .finally(() => {
          this.loading = false
        })
    }
}
</script>

<style scoped>
.user-home {
  min-height: 100vh;
  padding: 40px;
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #f5f7fa;
}

.user-home h2 {
  margin-bottom: 30px;
  color: #333;
}

.user-home .el-card {
  width: 80%;
  max-width: 1000px;
  margin-bottom: 20px;
}
</style>
